package com.wasion.gydpe.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import com.wasion.gydpe.dao.BureauDao;
import com.wasion.gydpe.dao.LineDao;
import com.wasion.gydpe.dao.StationDao;
import com.wasion.gydpe.dao.SvgDao;
import com.wasion.gydpe.dao.TerminalDao;
import com.wasion.gydpe.exception.DataAccessException;
import com.wasion.gydpe.model.Bureau;
import com.wasion.gydpe.model.Line;
import com.wasion.gydpe.model.Node;
import com.wasion.gydpe.model.Station;
import com.wasion.gydpe.model.Svg;
import com.wasion.gydpe.model.Terminal;
import com.wasion.gydpe.service.ArchivesService;

/**
 * 
 * @ClassName: ArchivesServiceImpl
 * @Description: 档案管理业务实现ServiceImpl
 * @author 高意
 * @date Sep 25, 2012 10:01:31 AM
 * 
 */
@Service
public class ArchivesServiceImpl implements ArchivesService {

	// 供电局Dao
	@Resource
	private BureauDao bureauDao;

	// 供电所Dao
	@Resource
	private StationDao stationDao;

	// 线路Dao
	@Resource
	private LineDao lineDao;

	// svg Dao
	@Resource
	private SvgDao svgDao;

	// 终端dao
	@Resource
	private TerminalDao terminalDao;

	public JSONObject queryBureausByPaging(Map<String, Object> paramsMap)
			throws DataAccessException {

		List<Bureau> list = null;
		long count = 0;
		list = bureauDao.queryByPaging(paramsMap);
		count = bureauDao.count(paramsMap);

		Map<String, Object> jsonMap = new HashMap<String, Object>();// 定义map
		jsonMap.put("total", count);// total键 存放总记录数，必须的
		jsonMap.put("rows", list);// rows键 存放每页记录 list

		return JSONObject.fromObject(jsonMap);
	}

	public JSONObject loadBureauByPk(Map<String, Object> paramsMap)
			throws DataAccessException {

		Bureau model = bureauDao.query(paramsMap).get(0);

		return JSONObject.fromObject(model);
	}

	public boolean removeBureau(Map<String, Object> paramsMap)
			throws DataAccessException {

		return bureauDao.remove(paramsMap);
	}

	public String addOrModifyBureau(Map<String, Object> paramsMap)
			throws DataAccessException {

		String bureauId = (String) paramsMap.get("bureauId");
		String bureauNo = (String) paramsMap.get("bureauNo");
		String bureauName = (String) paramsMap.get("bureauName");
		String bureauAddr = (String) paramsMap.get("bureauAddr");
		String bureauTelephone = (String) paramsMap.get("bureauTelephone");

		Bureau bureau = new Bureau();
		bureau.setBureauNo(bureauNo);
		bureau.setBureauName(bureauName);
		bureau.setBureauAddr(bureauAddr);
		bureau.setBureauTelephone(bureauTelephone);

		String resultMsg = "";
		if (null == bureauId) {
			boolean isSucc = bureauDao.add(bureau) > 0 ? true : false;
			resultMsg = isSucc ? "新增成功！" : "新增失败！";
		} else {
			bureau.setBureauId(Long.parseLong(bureauId));
			boolean isSucc = bureauDao.modify(bureau);
			resultMsg = isSucc ? "修改成功！" : "修改失败！";
		}

		return resultMsg;
	}

	public List<Bureau> queryAllBureaus() throws DataAccessException {

		return bureauDao.query();
	}

	public JSONObject queryStationsByPaging(Map<String, Object> paramsMap)
			throws DataAccessException {

		List<Station> list = null;
		long count = 0;
		list = stationDao.queryByPaging(paramsMap);
		count = stationDao.count(paramsMap);

		Map<String, Object> jsonMap = new HashMap<String, Object>();// 定义map
		jsonMap.put("total", count);// total键 存放总记录数，必须的
		jsonMap.put("rows", list);// rows键 存放每页记录 list

		return JSONObject.fromObject(jsonMap);
	}

	public JSONObject loadStationByPk(Map<String, Object> paramsMap)
			throws DataAccessException {

		Station model = stationDao.query(paramsMap).get(0);

		return JSONObject.fromObject(model);
	}

	public boolean removeStation(Map<String, Object> paramsMap)
			throws DataAccessException {

		return stationDao.remove(paramsMap);
	}

	public String addOrModifyStation(Map<String, Object> paramsMap)
			throws DataAccessException {

		String stationId = (String) paramsMap.get("stationId");
		String bureauId = (String) paramsMap.get("bureauId");
		String stationNo = (String) paramsMap.get("stationNo");
		String stationName = (String) paramsMap.get("stationName");
		String stationAddr = (String) paramsMap.get("stationAddr");
		String stationTelephone = (String) paramsMap.get("stationTelephone");

		Station station = new Station();
		station.setStationNo(stationNo);
		station.setBureauId(bureauId);
		station.setStationName(stationName);
		station.setStationAddr(stationAddr);
		station.setStationAddr(stationAddr);
		station.setStationTelephone(stationTelephone);

		String resultMsg = "";
		if (null == stationId) {
			boolean isSucc = stationDao.add(station) > 0 ? true : false;
			resultMsg = isSucc ? "新增成功！" : "新增失败！";
		} else {
			station.setStationId(Long.parseLong(stationId));
			boolean isSucc = stationDao.modify(station);
			resultMsg = isSucc ? "修改成功！" : "修改失败！";
		}

		return resultMsg;
	}

	public JSONObject queryLinesByPaging(Map<String, Object> paramsMap)
			throws DataAccessException {

		List<Line> list = null;
		long count = 0;
		list = lineDao.queryByPaging(paramsMap);
		count = lineDao.count(paramsMap);

		Map<String, Object> jsonMap = new HashMap<String, Object>();// 定义map
		jsonMap.put("total", count);// total键 存放总记录数，必须的
		jsonMap.put("rows", list);// rows键 存放每页记录 list

		return JSONObject.fromObject(jsonMap);
	}

	public JSONObject loadLineByPk(Map<String, Object> paramsMap)
			throws DataAccessException {

		Line model = lineDao.query(paramsMap).get(0);

		return JSONObject.fromObject(model);
	}

	public boolean removeLine(Map<String, Object> paramsMap)
			throws DataAccessException {

		List<Line> line = lineDao.query(paramsMap);

		boolean isSucc = lineDao.remove(paramsMap);

		paramsMap.put("svgId", line.get(0).getSvgId());
		isSucc = svgDao.remove(paramsMap);

		return isSucc;
	}

	public String addOrModifyLine(Map<String, Object> paramsMap)
			throws DataAccessException {

		String lineId = (String) paramsMap.get("lineId");
		String lineNo = (String) paramsMap.get("lineNo");
		String stationId = (String) paramsMap.get("stationId");
		String lineName = (String) paramsMap.get("lineName");
		String svgId = (String) paramsMap.get("svgId");
		String svgFilePath = (String) paramsMap.get("svgFilePath");

		Svg svg = new Svg();
		svg.setSvgName(lineName);
		svg.setSvgFileContent(null);
		svg.setSvgFilePath(svgFilePath);

		Line line = new Line();
		line.setLineNo(lineNo);
		line.setStationId(Long.parseLong(stationId));
		line.setLineName(lineName);

		String resultMsg = "";
		if (null == lineId) {
			boolean isSucc = svgDao.add(svg) > 0 ? true : false;

			line.setSvgId(svg.getSvgId());
			isSucc = lineDao.add(line) > 0 ? true : false;

			resultMsg = isSucc ? "新增成功！" : "新增失败！";
		} else {
			line.setLineId(Long.parseLong(lineId));
			line.setSvgId(Long.parseLong(svgId));
			boolean isSucc = lineDao.modify(line);

			svg.setSvgId(line.getSvgId());
			isSucc = svgDao.modify(svg);
			resultMsg = isSucc ? "修改成功！" : "修改失败！";
		}

		return resultMsg;
	}

	public List<Station> queryStationsBelonged(Map<String, Object> param)
			throws DataAccessException {

		return stationDao.query(param);
	}

	public JSONObject queryTerminalsByPaging(Map<String, Object> paramsMap)
			throws DataAccessException {

		List<Terminal> list = null;
		long count = 0;
		list = terminalDao.queryByPaging(paramsMap);
		count = terminalDao.count(paramsMap);

		Map<String, Object> jsonMap = new HashMap<String, Object>();// 定义map
		jsonMap.put("total", count);// total键 存放总记录数，必须的
		jsonMap.put("rows", list);// rows键 存放每页记录 list

		return JSONObject.fromObject(jsonMap);
	}

	public JSONObject loadTerminalByPk(Map<String, Object> paramsMap)
			throws DataAccessException {

		Terminal terminal = terminalDao.query(paramsMap).get(0);

		return JSONObject.fromObject(terminal);
	}

	public List<Line> queryLinesBelonged(Map<String, Object> param)
			throws DataAccessException {

		return lineDao.query(param);
	}

	public List<Node> queryAsyncTree(Map<String, Object> param)
			throws DataAccessException {

		List<Node> treeNodeList = new ArrayList<Node>();

		String id = (String) param.get("id");
		int level = (Integer) param.get("level");
		String state = "";
		Map<String, Object> localParams = new HashMap<String, Object>();
		// 查询前两级（供电局、供电所）
		if (null == id) {
			List<Bureau> bureauList = bureauDao.query(null);
			Iterator<Bureau> iterator = bureauList.iterator();
			while (iterator.hasNext()) {

				Bureau bureau = (Bureau) iterator.next();
				localParams.put("bureauId", bureau.getBureauId());
				List<Station> stationList = stationDao.query(localParams);
				List<Node> children = new ArrayList<Node>();

				Iterator<Station> subIterator = stationList.iterator();
				while (subIterator.hasNext()) {

					Station station = (Station) subIterator.next();
					Node subNode = new Node();
					subNode.setId(bureau.getBureauId() + "_"
							+ station.getStationId());
					if (level == 2) {
						Map<String, Object> attributes = new HashMap<String, Object>();
						attributes.put("leaf", true);
						subNode.setAttributes(attributes);
					} else {
						param.put("stationId", station.getStationId());
						state = lineDao.count(param) > 0 ? "closed" : "open";
						subNode.setState(state);
					}

					subNode.setIconCls("icon-station");
					subNode.setText(station.getStationName());
					children.add(subNode);
				}

				Node node = new Node();
				node.setId(bureau.getBureauId() + "");
				node.setIconCls("icon-bureau");
				node.setText(bureau.getBureauName());
				node.setChildren(children);

				treeNodeList.add(node);
			}
		} else {
			// 按“_”分割id，取最后一位，即为查询该节点的所有子节点
			String[] conIdArray = id.split("_");
			String subId = conIdArray[conIdArray.length - 1];

			// 查询当前节点下的所有线路
			if (2 == conIdArray.length) {
				param.put("stationId", subId);
				List<Line> lineList = lineDao.query(param);

				Iterator<Line> iterator = lineList.iterator();
				while (iterator.hasNext()) {
					Line line = (Line) iterator.next();

					Node subNode = new Node();
					subNode.setId(id + "_" + line.getLineId());
					subNode.setText(line.getLineName());
					subNode.setIconCls("icon-line");

					param.put("lineId", line.getLineId());
					state = terminalDao.count(param) > 0
							&& level - 1 > conIdArray.length ? "closed"
							: "open";
					subNode.setState(state);

					// 如果不为叶子节点，则该节点可以展开
					if (level - 1 == conIdArray.length) {
						Map<String, Object> attributes = new HashMap<String, Object>();
						attributes.put("leaf", true);
						subNode.setAttributes(attributes);
					}
					treeNodeList.add(subNode);
				}
			} else if (3 == conIdArray.length) { // 查询当前节点的所有终端

				param.put("lineId", subId);
				List<Terminal> terminalList = terminalDao.query(param);

				Iterator<Terminal> iterator = terminalList.iterator();
				while (iterator.hasNext()) {
					Terminal terminal = iterator.next();

					Node subNode = new Node();
					subNode.setId(id + "_" + terminal.getTerminalId());
					subNode.setText(terminal.getTerminalAddr());
					subNode.setIconCls("icon-terminal");
					// state = terminalDao.count(param) > 0 ? "closed" : "open";
					// subNode.setState(state);

					// 如果不为叶子节点，则该节点可以展开
					if (level - 1 == conIdArray.length) {
						Map<String, Object> attributes = new HashMap<String, Object>();
						attributes.put("leaf", true);
						subNode.setAttributes(attributes);
					}
					treeNodeList.add(subNode);
				}
			}
		}

		return treeNodeList;
	}
}
